package com.gancp.common.security;

import com.gancp.common.Constans;
import com.gancp.domain.User;
import com.gancp.service.UserBiz;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * Created by GCP on 2018/5/27.
 * 自定义的登录信息管理器（通俗的就是将用户session存储，统一管理）
 */
public class MyRealm extends AuthorizingRealm {

    @Autowired
    private UserBiz userBiz;

    /**
     * @Author gancp
     * @Date 时间被黑洞吸走了
     * @Descripition 加载权限
     **/
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        String username = (String) principalCollection.getPrimaryPrincipal();
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();


        // TODO 加载用户权限
        authorizationInfo.addStringPermission( "" );


        return authorizationInfo;
    }

    /**
     * @Author gancp
     * @Date 时间被黑洞吸走了
     * @Descripition 认证和登录
     **/
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        String userName = token.getUsername();
        User user = null;
        try {
            user = userBiz.findUserByUserName( userName );
            if (null == user) {
                return null;
            } else {
                AuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo( user.getUsername(), user.getPassword(), getName() );
                SecurityUtils.getSubject().getSession().setAttribute( Constans.USER_INFO, user );
                return authenticationInfo;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
